<?php

namespace frontend\controllers;

use Yii;
use common\models\Post;
use yii\web\Controller;
use common\components\SubjectHelper;
use yii\data\Pagination;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * PostController implements the CRUD actions for Post model.
 */
class PostController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            // index页面缓存，1天有效
            'indexCache' => [
                'class' => 'common\components\PageCache',
                'only' => ['index'],
                'duration' => 86400,
                'variations' => [\Yii::$app->language,],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT `id` FROM `post` ORDER BY `id` DESC LIMIT 1',
                ],
            ],            
            // view页面缓存，永久有效
            'viewCache' => [
                'class' => 'common\components\PageCache',
                'only' => ['view'],
                'duration' => 1,
                'variations' => [\Yii::$app->language,],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT `updated_at` FROM `post` ORDER BY `id` DESC LIMIT 1',
                ],
            ],
            // topic页面缓存，1天有效
            'topicCache' => [
                'class' => 'common\components\PageCache',
                'only' => ['topic'],
                'duration' => 86400,
                'variations' => [\Yii::$app->language,],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT `updated_at` FROM `post` WHERE tag="'.\Yii::$app->request->get('tag').'" ORDER BY `id` DESC LIMIT 1',
                ],
            ],
            // Http缓存
            'HttpCache' => [
                'class' => 'yii\filters\HttpCache',
                'only' => ['view'],
                'etagSeed' => function ($action, $params) {
                    $post = Post::find()->select(['id'])->orderBy('id desc')->limit(1)->asArray()->one();
                    return serialize([$post]);
                },
            ],
        ];
    }

    /**
     * Lists all Post models.
     * @return mixed
     */
    public function actionIndex() {
        $query = Post::find()->with('c')->where(['enable' => 1])->asArray();
        $pagination = new Pagination([
            'defaultPageSize' => 20,
            'totalCount' => $query->count(),
        ]);
        $model = $query->orderBy('id desc')
                ->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();
        $hot = Post::find()->with('c')->asArray()->orderBy('view desc')->limit(10)->all();
        $tag = SubjectHelper::PostTags();
        return $this->render('index', [
                    'model' => $model,
                    'hot' => $hot,
                    'tag' => $tag,
                    'pagination' => $pagination,
        ]);
    }

    /**
     * Displays a list Post model.
     * @param integer $tag
     * @return mixed
     */
    public function actionTopic($tag) {
        $query = Post::find()->where(['tag' => $tag])->andWhere(['enable' => 1])->with('c')->asArray();
        $pagination = new Pagination([
            'defaultPageSize' => 10,
            'totalCount' => $query->count(),
        ]);
        $model = $query->orderBy('id desc')
                ->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();
        $hot = Post::find()->with('c')->asArray()->orderBy('view desc')->limit(10)->all();
        $cache = Yii::$app->cache;
        $tags = $cache->get("tagPost");
        if ($tags === false) {
            $tags = SubjectHelper::PostTags();
            $cache->set("tagPost", $tags);
        }
        return $this->render('topic', [
                    'model' => $model,
                    'hot' => $hot,
                    'tag' => $tags,
                    'title' => $tag,
                    'pagination' => $pagination,
        ]);
    }

    /**
     * Displays a single Post model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        $model = Post::find()->where(['id' => $id])->andWhere(['enable' => 1])->with('c')->asArray()->one();
        if (!empty($model)) {
            $next = Post::find()->where(['>', 'id', $model['id']])->andWhere(['enable' => 1])
                            ->limit(1)->with('c')->asArray()->one();
            $last = Post::find()->where(['<', 'id', $model['id']])->andWhere(['enable' => 1])
                            ->orderBy(['id' => SORT_DESC])->limit(1)->with('c')->asArray()->one();
            if (!empty($model['tag'])) {
                $relate = Post::find()->select(['id', 'title'])->where(['like', 'tag', $model['tag']])->andWhere(['!=', 'id', $model['id']])
                                ->andWhere(['enable' => 1])->orderBy(['id' => SORT_DESC])
                                ->orderby('view desc')->limit(20)->asArray()->all();
            } else {
                $relate = Post::find()->select(['id', 'title'])->where(['cid' => $model['cid']])->andWhere(['!=', 'id', $model['id']])
                                ->andWhere(['enable' => 1])->orderBy(['id' => SORT_DESC])
                                ->orderby('view desc')->limit(20)->asArray()->all();
            }
            $cache = Yii::$app->cache;
            $tag = $cache->get("tagPost");
            if ($tag === false) {
                $tag = SubjectHelper::PostTags();
                $cache->set("tagPost", $tag);
            }            
            // 更新浏览量
            SubjectHelper::updateViews('post', $model['view'], $id);
            return $this->render('view', [
                        'model' => $model,
                        'last' => $last,
                        'next' => $next,
                        'relate' => $relate,
                        'tag' => $tag,
            ]);
        } else {
            throw new NotFoundHttpException(\Yii::t('common', 'NotFound'));
        }
    }

    /**
     * Finds the Post model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Post the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Post::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
